package com.dobbinsoft.iotechn.device.mqtt.handler;

import com.dobbinsoft.iotechn.ability.model.AbilityContext;
import com.dobbinsoft.iotechn.ability.model.DeviceOpenApiResultModel;
import com.dobbinsoft.iotechn.ability.openapi.IOpenApiManager;
import com.dobbinsoft.iotechn.device.enums.IotMessageResultType;
import com.dobbinsoft.iotechn.device.enums.IotMessageType;
import com.dobbinsoft.iotechn.device.mqtt.IotMqttClient;
import com.dobbinsoft.iotechn.device.mqtt.message.IotDeviceApiInvokeMessage;
import com.dobbinsoft.iotechn.device.mqtt.message.down.IotDeviceApiInvokeResultMessage;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Description:
 * User: rize
 * Date: 2020/7/7
 * Time: 17:22
 */
public class IotMqttApiInvokeMessageHandler implements IotMqttMessageHandler<IotDeviceApiInvokeMessage> {

    @Autowired
    private IOpenApiManager openApiManager;

    @Autowired
    private IotMqttClient iotMqttClient;

    @Override
    public int handle(String accessKeyId, IotDeviceApiInvokeMessage msg) {
        String name = msg.getName();
        String[] array = name.split("\\.");
        if (array.length != 2) {
            return IotMessageResultType.SUCCESS.getCode();
        }
        AbilityContext context = new AbilityContext();
        context.setAccessKeyId(accessKeyId);
        // TODO 设置IP
        context.setIp("");
        context.setParams(msg.getParams());
        DeviceOpenApiResultModel resultModel = openApiManager.invoke(array[0], array[1], msg.getInvokeId(), context);
        // 调用结果包装消息
        IotDeviceApiInvokeResultMessage message = new IotDeviceApiInvokeResultMessage();
        message.setInvokeId(msg.getInvokeId());
        message.setErrorCode(resultModel.getCode());
        message.setCode(IotMessageType.API_INVOKE_RES.getCode());
        message.setResult(resultModel.getRes());
        // 回复设备调用结果
        iotMqttClient.send(accessKeyId, message);
        return IotMessageResultType.SUCCESS.getCode();
    }

    @Override
    public int getCode() {
        return IotMessageType.API_INVOKE.getCode();
    }

    @Override
    public Class<IotDeviceApiInvokeMessage> getMessageType() {
        return IotDeviceApiInvokeMessage.class;
    }

}
